using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MyEFCore;

namespace TestBaseDbContext
{
    public class Test_BaseDbContext
    { 
        public Test_BaseDbContext()
        {
            var services = new ServiceCollection();

            services.AddSingleton<IConfiguration>(new ConfigurationBuilder().AddJsonFile("appsettings.json").Build());
            services.AddMyDbContext<MyDbContext>((options, conn) =>
            {
                options.UseSqlServer(conn);
            });

            Provider = services.BuildServiceProvider(); 
        }

        public ServiceProvider Provider { get; }

        [Fact]
        public async void Test()
        {
            var context = Provider.GetService<MyDbContext>();
            Assert.NotNull(context);

            var hasData = await context!.Set<Student>().AnyAsync();
            Assert.True(hasData);

            var students = await context!.Set<Student>().ToListAsync();
            Assert.True(students.Any());
        }

        [Theory]
        [InlineData("aaaa1", "2022-01-01")]
        //[InlineData("aaaa2", "2022-02-01")]
        //[InlineData("aaaa3", "2022-03-01")]
        //[InlineData("aaaa4", "2022-04-01")]
        public async void Test_CRUD(string name, string birth)
        {
            var student = new Student
            {
                Name = name,
                NickName = name,
                Birthday = DateTime.Parse(birth)
            };

            var context = Provider.GetService<MyDbContext>();
            Assert.NotNull(context);

            var entity = await context!.Set<Student>().FirstOrDefaultAsync(t => t.Name == name);
            if (entity is not null)
            {
                context!.Remove(entity);
                await context!.SaveChangesAsync();
            }

            await context!.Set<Student>().AddAsync(student);

            await context!.SaveChangesAsync();

            var success = await context!.Set<Student>().AnyAsync(t => t.Name == name);
            Assert.True(success);

            var student1 = await context!.Set<Student>().FirstAsync(t => t.Name == name);
            student1.Birthday = student1.Birthday.AddYears(-20);
            context!.Update(student1);
            await context!.SaveChangesAsync();

            var student2 = await context!.Set<Student>().FirstAsync(t => t.Name == name);
            Assert.True(student2.Birthday == DateTime.Parse(birth).AddYears(-20));

            context!.Set<Student>().Remove(student2);
            await context!.SaveChangesAsync();

            var exist = await context!.Set<Student>().AnyAsync(t => t.Name == name);
            Assert.False(exist);
        }
    }
}